package com.cmcc.example.face.common.util;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 樊欣
 * @version 1.0
 * OkHttp 处理请求
 * @date 创建时间：2018年05月04日 下午11:18
 */
public class HttpUtil {

    Logger log = LoggerFactory.getLogger(HttpUtil.class);
    private static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS).build();

    private volatile static HttpUtil INSTANCE;

    private final static String AUTHORIZATION = "4837f3259dce7325d403c8cf84dad1bd";

    private HttpUtil() {
    }

    public static HttpUtil instance() {
        if (INSTANCE == null) {
            synchronized (HttpUtil.class) {
                if (INSTANCE == null) {
                    INSTANCE = new HttpUtil();
                }
            }
        }
        return INSTANCE;
    }

    public String httpGet(String url) {
        return httpRequest(url, "", "", "GET");
    }

    public String httpPostJson(String url, String body) {
        return httpRequest(url, body, "application/json; charset=utf-8", "POST");
    }

    public String httpPostForm(String url, Map<String, String> body) {
        return httpFormRequest(url, body);
    }

    public String httpRequest(String url, String body, String contentType, List<HeaderInfo> headerInfoList, String method) {
        Request.Builder builder = new Request.Builder();
        Headers.Builder headerBuilder = new Headers.Builder();
        String responseString = "";
        try {
            if (!CheckOutUtil.ListIsEmpty(headerInfoList)) {
                headerInfoList.stream().forEach(headerInfo -> {
                    headerBuilder.add(headerInfo.key, headerInfo.value);
                });
            }
            if ("GET".equals(method)) {
                builder.url(url);
            }
            else if ("POST".equals(method)) {
                RequestBody requestBody = RequestBody.create(MediaType.parse(contentType), body);
                builder.headers(headerBuilder.build()).url(url).post(requestBody);
            }
            if (null != builder.build()) {
                Response response = client.newCall(builder.build()).execute();
                if (response.isSuccessful()) {
                    responseString = response.body().string();
                }
                else {
                    log.warn("HttpUtil httpRequest response is not success url:{} body:{} contentType:{} method:{}", url, body, contentType, method);
                }
            }
        } catch (IOException e) {
            log.error("HttpUtil http request get exception! url:{} body:{} contentType:{} method:{} \nexception -> {}", url, body, contentType, method, e);
        }
        return responseString;
    }

    public String httpRequest(String url, String body, String contentType, String method) {
        String result = "";
        Request.Builder builder = new Request.Builder();
        try {
            if (method.equals("GET")) {
                builder = new Request.Builder().url(url);
            }

            if (method.equals("POST")) {
                RequestBody requestBody = FormBody.create(MediaType.parse(contentType), body);
                builder = new Request.Builder().addHeader("Authorization", AUTHORIZATION).url(url).post(requestBody);
            }

            Request request = builder.build();
            if (request != null) {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    result = response.body().string();
                }else {
                    log.info("HttpUtil httpRequest response is failure, url : {}, body : {}", url, body);
                }
            } else {
                log.info("HttpUtil httpRequest is null, url : {}, body : {}", url, body);
            }

        } catch (Exception e) {
            log.error("HttpUtil httpRequest -> Exception = {}, url = {}, body = {}", e, url, body);
        }
        return result;

    }

    public String httpFormRequest(String url, Map<String, String> body) {
        String result = "";
        Request request;
        try {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : body.entrySet()
                    ) {
                builder.add(entry.getKey(), entry.getValue());
            }

            RequestBody formBody = builder.build();
            request = new Request.Builder()
                    .url(url)
                    .post(formBody)
                    .build();

            if(request != null){
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    result = response.body().string();
                }else {
                    log.info("HttpUtil httpRequest response is failure, url : {}, body : {}", url, body.toString());
                }
            }else {
                log.info("HttpUtil httpRequest is null, url : {}, body : {}", url, body);
            }

        } catch (Exception e) {
            log.error("HttpUtil httpRequest -> Exception = {}, url = {}, body = {}", e, url, body.toString());
        }
        return result;
    }

    public static class HeaderInfo {
        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        private String key;
        private String value;
    }
}
